package com.studentmanagement.ui;

import com.studentmanagement.model.Student;
import com.studentmanagement.model.Teacher;
import com.studentmanagement.model.User;
import com.studentmanagement.service.StudentService;
import com.studentmanagement.service.TeacherService;
import com.formdev.flatlaf.FlatClientProperties;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

public class PersonalInfoPanel extends JPanel {
    private User currentUser;
    private StudentService studentService;
    private TeacherService teacherService;
    
    // 表单字段
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JPasswordField confirmPasswordField;
    private JTextField nameField;
    private JComboBox<String> genderComboBox;
    private JTextField departmentField;
    private JTextField contactField;
    private JTextField emailField;
    private JTextField idField; // 学号或工号
    private JTextField majorField; // 仅学生
    private JTextField titleField; // 仅教师
    
    private JButton saveButton;
    private JButton resetButton;

    public PersonalInfoPanel(User user) {
        this.currentUser = user;
        this.studentService = new StudentService();
        this.teacherService = new TeacherService();
        
        initComponents();
        setupLayout();
        setupListeners();
        loadUserInfo();
    }

    private void initComponents() {
        // 初始化表单字段
        usernameField = new JTextField(20);
        usernameField.setEditable(false);
        passwordField = new JPasswordField(20);
        confirmPasswordField = new JPasswordField(20);
        nameField = new JTextField(20);
        genderComboBox = new JComboBox<>(new String[]{"男", "女", "其他"});
        departmentField = new JTextField(20);
        contactField = new JTextField(20);
        emailField = new JTextField(20);
        idField = new JTextField(20);
        majorField = new JTextField(20);
        titleField = new JTextField(20);
        
        saveButton = new JButton("保存修改");
        resetButton = new JButton("重置");

        // 设置字体
        Font font = new Font("微软雅黑", Font.PLAIN, 14);
        usernameField.setFont(font);
        passwordField.setFont(font);
        confirmPasswordField.setFont(font);
        nameField.setFont(font);
        genderComboBox.setFont(font);
        departmentField.setFont(font);
        contactField.setFont(font);
        emailField.setFont(font);
        idField.setFont(font);
        majorField.setFont(font);
        titleField.setFont(font);
        saveButton.setFont(font);
        resetButton.setFont(font);

        // 设置提示文本
        passwordField.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "输入新密码(不修改请留空)");
        confirmPasswordField.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "确认新密码");
        contactField.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "请输入联系电话");
        emailField.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "请输入电子邮箱");
    }

    private void setupLayout() {
        setLayout(new BorderLayout(20, 20));
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建标题面板
        JPanel titlePanel = new JPanel();
        JLabel titleLabel = new JLabel("个人信息");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titlePanel.add(titleLabel);

        // 创建表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        // 添加表单字段
        int row = 0;
        addFormField(formPanel, "用户名:", usernameField, gbc, row++);
        addFormField(formPanel, "新密码:", passwordField, gbc, row++);
        addFormField(formPanel, "确认密码:", confirmPasswordField, gbc, row++);
        addFormField(formPanel, "姓名:", nameField, gbc, row++);
        addFormField(formPanel, "性别:", genderComboBox, gbc, row++);
        
        if (currentUser.getRole() == User.UserRole.STUDENT) {
            addFormField(formPanel, "学号:", idField, gbc, row++);
            addFormField(formPanel, "专业:", majorField, gbc, row++);
        } else if (currentUser.getRole() == User.UserRole.TEACHER) {
            addFormField(formPanel, "工号:", idField, gbc, row++);
            addFormField(formPanel, "职称:", titleField, gbc, row++);
        }
        
        addFormField(formPanel, "院系:", departmentField, gbc, row++);
        addFormField(formPanel, "联系电话:", contactField, gbc, row++);
        addFormField(formPanel, "电子邮箱:", emailField, gbc, row++);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0));
        saveButton.setPreferredSize(new Dimension(120, 40));
        resetButton.setPreferredSize(new Dimension(120, 40));
        
        // 设置按钮样式
        saveButton.putClientProperty(FlatClientProperties.STYLE, "arc: 10");
        saveButton.setBackground(new Color(52, 152, 219));
        saveButton.setForeground(Color.WHITE);
        
        resetButton.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_BORDERLESS);
        resetButton.setForeground(new Color(149, 165, 166));
        
        buttonPanel.add(saveButton);
        buttonPanel.add(resetButton);

        // 将所有面板添加到主面板
        add(titlePanel, BorderLayout.NORTH);
        add(new JScrollPane(formPanel), BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void addFormField(JPanel panel, String label, JComponent field, GridBagConstraints gbc, int row) {
        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.anchor = GridBagConstraints.EAST;
        panel.add(new JLabel(label), gbc);
        
        gbc.gridx = 1;
        gbc.anchor = GridBagConstraints.WEST;
        panel.add(field, gbc);
    }

    private void setupListeners() {
        saveButton.addActionListener(this::onSave);
        resetButton.addActionListener(e -> loadUserInfo());
    }

    private void loadUserInfo() {
        usernameField.setText(currentUser.getUsername());
        passwordField.setText("");
        confirmPasswordField.setText("");

        if (currentUser.getRole() == User.UserRole.STUDENT) {
            Student student = studentService.getStudentByUserId(currentUser.getId());
            if (student != null) {
                nameField.setText(student.getName());
                genderComboBox.setSelectedItem(formatGender(student.getGender()));
                departmentField.setText(student.getDepartment());
                contactField.setText(student.getContactNumber());
                emailField.setText(student.getEmail());
                idField.setText(student.getStudentId());
                majorField.setText(student.getMajor());
            }
        } else if (currentUser.getRole() == User.UserRole.TEACHER) {
            Teacher teacher = teacherService.getTeacherByUserId(currentUser.getId());
            if (teacher != null) {
                nameField.setText(teacher.getName());
                genderComboBox.setSelectedItem(formatGender(teacher.getGender()));
                departmentField.setText(teacher.getDepartment());
                contactField.setText(teacher.getContactNumber());
                emailField.setText(teacher.getEmail());
                idField.setText(teacher.getTeacherId());
                titleField.setText(teacher.getTitle());
            }
        }
    }

    private void onSave(ActionEvent e) {
        // 验证密码
        String password = new String(passwordField.getPassword());
        String confirmPassword = new String(confirmPasswordField.getPassword());
        if (!password.isEmpty() && !password.equals(confirmPassword)) {
            JOptionPane.showMessageDialog(this, "两次输入的密码不一致！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 验证必填字段
        if (nameField.getText().trim().isEmpty() || idField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "姓名和学号/工号不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        boolean success = false;
        if (currentUser.getRole() == User.UserRole.STUDENT) {
            Student student = new Student();
            student.setUserId(currentUser.getId());
            student.setStudentId(idField.getText().trim());
            student.setName(nameField.getText().trim());
            student.setGender(parseGender((String)genderComboBox.getSelectedItem()));
            student.setDepartment(departmentField.getText().trim());
            student.setMajor(majorField.getText().trim());
            student.setContactNumber(contactField.getText().trim());
            student.setEmail(emailField.getText().trim());
            success = studentService.updateStudent(student);
        } else if (currentUser.getRole() == User.UserRole.TEACHER) {
            Teacher teacher = new Teacher();
            teacher.setUserId(currentUser.getId());
            teacher.setTeacherId(idField.getText().trim());
            teacher.setName(nameField.getText().trim());
            teacher.setGender(parseGender((String)genderComboBox.getSelectedItem()));
            teacher.setDepartment(departmentField.getText().trim());
            teacher.setTitle(titleField.getText().trim());
            teacher.setContactNumber(contactField.getText().trim());
            teacher.setEmail(emailField.getText().trim());
            success = teacherService.updateTeacher(teacher);
        }

        if (success) {
            // 如果密码不为空，更新密码
            if (!password.isEmpty()) {
                // TODO: 实现更新密码的逻辑
            }
            JOptionPane.showMessageDialog(this, "保存成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(this, "保存失败！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private String formatGender(String gender) {
        if (gender == null) return "其他";
        switch (gender.toUpperCase()) {
            case "MALE": return "男";
            case "FEMALE": return "女";
            default: return "其他";
        }
    }

    private String parseGender(String displayGender) {
        switch (displayGender) {
            case "男": return "MALE";
            case "女": return "FEMALE";
            default: return "OTHER";
        }
    }
} 